const API = require("../../utils/api")
const app = getApp()
// pages/park/park.js
Page({

    /**
     * 页面的初始数据
     */
    data: { 
        detail:'',
        gardenId: '',
        tabCurrent: 0,
        page:'pages/park/park',
        canvasShow: false,
        articleList:[],
        companyPageNum: 1,
        articlePageNum: 1,
        reachBottomShow: true,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log('园区接收传参二维码qrQuery', decodeURIComponent(options.scene))
        //2. 获取启动参数 二维码
        if( options && options.scene ){ 
            //重置登陆状态
            app.globalData.userInfo = {}
            app.globalData.hasUserInfo = false
    
            let query = {}
            let scene = decodeURIComponent(options.scene).split('&')
            scene.forEach( ele => {
                let key = ele.split('=')[0]
                query[key] = ele.split('=')[1]
            })
            console.log('格式化启动参数', query)
            let globalQuery = {
                userId: query.uid,
                spreadType: query.st,
                type: query.t,
            }
            query.yqid ? globalQuery.gardenId = query.yqid : ''
            query.qyid ? globalQuery.enterpriseId = query.qyid : ''
            app.globalData.inviterUserId = query.uid
            app.globalData.qrQuery = globalQuery
        }

        if( options && options.inviterUserId ){ //分享绑定
            app.globalData.inviterUserId = options.inviterUserId
        }
        if( options && options.id ){ //页面传参
            console.log('园区接收传参options', options)
            this.setData({
                gardenId: options.id, 
                // gardenId: 292
            })
        }else if( app.globalData.qrQuery && app.globalData.qrQuery.gardenId ){ //二维码传参
            console.log('园区接收传参qrQuery', app.globalData.qrQuery)
            this.setData({
                gardenId: app.globalData.qrQuery.gardenId 
            })
        }

        this.get_park_detail()
        this.get_housingAreaList()
        this.get_house_areaIdList()
        this.get_garden_article_list()
        this.get_park_company_list()

        //微信推广 - 定位到房源
        if( options && options.site && options.site == 1 ){
            wx.pageScrollTo({
                selector: '#site_house',
                duration: 300
            })
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function(){
        let that = this
        // let hasUserInfo = app.globalData.hasUserInfo
        // if( !hasUserInfo ){
        //     wx.reLaunch({
        //       url: '/pages/login/login?back=/pages/park/park&id=' + that.data.gardenId,
        //     })
        // }
    },

    /**
     * 触底事件
     */
    onReachBottom:function(){ 
        if(this.data.reachBottomShow){
            let articlePageNum = this.data.articlePageNum
            articlePageNum++
            this.setData({
                articlePageNum
            })
            // console.log('分页', articlePageNum)
            this.get_garden_article_list()
        }
    },

    /**
     * 接口 - 获取园区详情
     */
    get_park_detail:function(){
        let that = this
        const userInfo = wx.getStorageSync('userInfo')
        API.get_park_detail({
            id: that.data.gardenId,
            wxUserid: userInfo.id,
            sourse: 1,
        }).then( res => {
            if( res.code == 200 ){
                let detail = res.data
                detail.honorCertification ? detail.honorCertification = detail.honorCertification.split(',') : ''
                if(detail.serviceTime != null){
                    detail.serviceTime = detail.serviceTime.substr(0,10)
                }
                console.log('园区详情',detail)
                that.setData({
                    detail: detail
                })
            }
        })
    },

    /**
     * 接口 - 获取面积
     */
    get_housingAreaList:function(){
        let that = this
        API.get_housingAreaList({
            gardenId: that.data.gardenId
        }).then( res => {
            if( res.code == 200 ){
                //排序 从小到大
                let rows = res.rows.sort( (a, b) => {
                    return a['id'] - b['id']
                })
                that.setData({
                    housingAreaList: rows
                })
            }
        })
    },

    /**
     * 接口 - 获取房源列表
     */
    get_house_areaIdList:function(areaId = ''){
        let that = this
        wx.showLoading({
          title: '加载中',
        })
        API.get_house_areaIdList({
            areaId: areaId,
            gardenId: that.data.gardenId,
            pageSize: 10,
            pageNum: 1,
        }).then( res => {
            if( res.code == 200 ){
                that.setData({
                    houseList: res.rows
                })
                wx.hideLoading()
            }
        })
    },

    /**
     * 接口 - 获取文章信息
     */
    get_garden_article_list:function(){
        let that = this
        API.get_garden_article_list({
            gardenId: that.data.gardenId,
            pageNum: that.data.articlePageNum,
            pageSize: 10
        }).then( res => {
            if( res.code == 200 ){
                that.setData({
                    articleList: [...that.data.articleList, ...res.rows]
                })
                if( res.total <= that.data.articlePageNum * 10 ){
                    that.setData({
                        reachBottomShow: false
                    })
                }
            }
        })
    },

    /**
     * 查询当前园区企业列表
     */
    get_park_company_list:function(){
        let that = this
        API.get_park_company_list({
            id: that.data.gardenId,
            pageNum: that.data.companyPageNum,
            pageSize: 10
        }).then( res => {
            if( res.code == 200 ){
                console.log(res)
                that.setData({
                    parkCompanyList: res.rows
                })
            }
        })
    },

    /**
     * 事件 - 招商房源面积点击事件
     */
    houseTabChange:function(e){
        let id = e.currentTarget.id
        this.setData({
            tabCurrent: e.currentTarget.dataset.index
        })
        console.log(id)
        if( id != 0 ){
            this.get_house_areaIdList(id)
        }else{
            this.get_house_areaIdList()
        }
    },

    /**
     * 查看文章详情
     */
    viewDetail:function(e){
        wx.navigateTo({
          url: '/pages/share/detail/detail?type=2&id=' + e.currentTarget.dataset.item.id,
        })
    },

    /**
     * 事件 - 加微信
     */
    addWxFriend:function(){
        app.contact()
        this.add_park_customer()
    },

    /**
     * 事件 - 电话联系
     */
    callPhone:function(){
        wx.makePhoneCall({
            phoneNumber: this.data.detail.phone
        })
        this.add_park_customer()
    },

    /**
     * 事件 - 打开宣传手册
     */
    viewBrochure:function(){
        wx.downloadFile({
            url: this.data.detail.brochure,
            success: function (res) {
              const filePath = res.tempFilePath
              wx.openDocument({
                filePath: filePath,
                success: function (res) {
                  console.log('打开文档成功')
                }
              })
            }
        })
    },

    /**
     * 路由 - 园区管理
     */
    routeJoin:function(){
        let that = this
        if( !app.globalData.hasUserInfo ){
            wx.showToast({
                title: '您还没有登陆哦',
                icon:'none'
            })
              
            setTimeout( () => {
                wx.reLaunch({
                    url: '/pages/login/login?back=/pages/park/park&parkId=' + that.data.detail.id,
                })
            },1000)
            return
        }
        wx.navigateTo({
          url: '/pages/mine/park-manage/park-manage?id=' + that.data.detail.id + '&cardId=' + that.data.detail.cardId,
        })
    },

    /**
     * 路由 - 企业主页
     */
    routeCompany:function(e){
        let item = e.currentTarget.dataset.item
        if( item.sign != 2 || !item.enterpriseId ){
            wx.navigateTo({
                url: '/pages/park/company/company?id=' + item.id + '&type=2',
            })
            // wx.showToast({
            //   title: '该企业未认证，暂不可查看',
            //   icon:'none'
            // })
            return
        }
        wx.navigateTo({
          url: '/pages/park/company/company?id=' + item.enterpriseId,
        })
    },

    /**
     * 路由 - 名片
     */
    routeContact:function(){
        let that = this
        wx.navigateTo({
            url: '/pages/park/visiting-card/visiting-card?id=' + that.data.detail.cardId,
        })
        this.add_park_customer()
    }, 

    /**
     * 路由 - 更多企业
     */
    moreCompany:function(){
        console.log(this.data.detail)
        wx.navigateTo({
          url: '/pages/park/more/company/company?id=' + this.data.detail.id,
        })
    },

    /**
     * 路由 - 房源详情
     */
    routeHouseDetail:function(e){
        console.log( '园区详情', this.data.detail )
        let id = e.currentTarget.id
        // let cardId = this.data.detail.cardId
        // let name = this.data.detail.name
        // let phone = this.data.detail.phone
        // let post = this.data.detail.post
        // let weChat = this.data.detail.weChat
        // let headImg = this.data.detail.headImg
        // let gardenName = this.data.detail.gardenName
        // let location = this.data.detail.location
        // let ambitus = this.data.detail.ambitus
        let query = 'id=' + id + '&gardenId=' + this.data.gardenId
        // + '&cardId=' + cardId + '&name=' + name + '&phone=' + phone + '&post=' + post + '&weChat=' + weChat + '&headImg=' + headImg + '&gardenName=' + gardenName + '&location=' + location + '&ambitus=' + ambitus
        wx.navigateTo({
          url: '/pages/park/house/detail?' + query,
        })
    },

    /**
     * 获取我的二维码
     */
    creat_wxmini_qrcode:function(){
        let that = this
        this.setData({
            canvasShow: true,
            canvasId: 'shareImg'  //+ Date.parse(new Date())
        })
        console.log('打开组件画图',this.data.canvasId)
    },

    /**
     * 接口 - 新增客户（进园区感兴趣）
     */
    add_park_customer:function(){
        let that = this
        API.add_park_customer({
            clientUserId: app.globalData.userInfo.id,
            gardenId: that.data.detail.id
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    onShareTimeline: function(){},
})